<?php
/**
 * Created by PhpStorm.
 * User: chniccs
 * Date: 2019-11-08
 * Time: 16:26
 */

namespace app\app\controller;


use app\helper\TokenHelper;
use app\helper\WxHelper;
use app\model\AdminTenant;
use app\model\AppWxUser;
use app\util\ReturnCode;
use EasyWeChat\Kernel\Exceptions\InvalidConfigException;
use Exception;
use think\facade\Request;

class Wx extends Base
{
    public function getSignature(){
        $url = $this->request->param('url');
        $apiStr = $this->request->param('apis');
        $apis = json_decode($apiStr);
        try {
            $this->getWx()->jssdk->setUrl($url);
            $data = $this->getWx()->jssdk->buildConfig($apis, $debug = true, $beta = false, $json = true);
            return $this->buildSuccess($data);
        } catch (InvalidConfigException $e) {
        }
        return $this->buildFailed(ReturnCode::FAILED,'获取签名失败');
    }
    /**
     * 获取公众号appid
     * @return \think\response\Json
     */
    public function getGzhAppid()
    {
        $model = AdminTenant::get($this->getUserTid());
        if ($model) {
            $data = $model->getData();
            return $this->buildSuccess($data['gzh_appid']);
        } else {
            return $this->buildFailed(ReturnCode::INVALID, '获取失败');
        }
    }

    public function wxLogin()
    {
        $code = Request::param('code');
        $invid = Request::param('invid');
        try {
            $model = AdminTenant::get($this->getUserTid(),null,false);
            if ($model) {
                $data = $model->getData();
                $result = WxHelper::getWxUserInfo($data['gzh_appid'],$data['gzh_secret'],$code);
                if(isset($invid)){
                    $result['invid'] = $invid;
                }
                $result = $this->addTid($result);
                $checkReuslt = (new AppWxUser())->checkWxUser($result);
                if($checkReuslt['done']){
                    $res = $checkReuslt['user_info'];
                    $res['uid'] = $res['id'];
                    $apiAuth = TokenHelper::setAppToken($res['uid'],$res);
                    $rep['token'] = $apiAuth;
                    $rep['userinfo'] = $res;
                    return $this->buildSuccess($rep);
                }
            }
        }catch (Exception $e){
        }
        return $this->buildFailed(ReturnCode::AUTH_ERROR,'');
    }

}